package api

import (
	beego "github.com/beego/beego/v2/adapter"
	"weiboxs.com/new_h_glasses/services"
	"strings"
	"weiboxs.com/new_h_glasses/utils"
	"weiboxs.com/new_h_glasses/models"
	"strconv"
	)

type ApiWechatController struct {
	beego.Controller
}

//微信推送接口
func (c *ApiWechatController) WechatIndex() {
	ser := services.WechatApiService{}
	ser.WechatIndex(c.Ctx)
	c.StopRun()
}

//微信消息展示
func (c *ApiWechatController) Message() {

	encode := c.GetString("encode")
	idstr, err := utils.Decrypt(encode)
	if err != nil {
		c.message("参数传递错误", 500, "")
		return
	}

	id, err := strconv.ParseInt(idstr, 10, 64)
	if err != nil {
		c.message("参数传递错误", 500, "")
		return
	}
	model := models.WechatMessage{}
	data := model.One(id,0)
	c.Data["details"] = data
	c.Data["pageTitle"] = data.Title

	c.display("", "api/wechat/message_footerjs.html")
}

//jsSDK
func (c *ApiWechatController) JsSdk() {
	uri := c.GetString("uri")
	//设置微信分享信息
	ser := services.WechatApiService{}
	jssdk, errs := ser.JsSdk(uri)
	if errs != nil {
		utils.LogAlert(errs)
		c.Data["json"] =  &models.JsonResult{1, errs.Error(), ""}
	} else {
		c.Data["json"] =  &models.JsonResult{0, "ok", jssdk}
	}
	c.ServeJSON()
}

//设置错误信息
func (c *ApiWechatController) message(info string, code int, backurl string) bool {
	c.Data["message"] = info
	c.Data["code"] = code
	c.Data["backurl"] = backurl
	c.display("api/message.html")
	return false
}

//查看验光数据
func (c *ApiWechatController) ShowOptometry() {

}

// 设置模板，第一个参数模板，第二个参数为扩展JS，第三个为layout
func (c *ApiWechatController) display(template ...string) {
	var tplName string
	layout := "api/layout.html"
	c.LayoutSections = make(map[string]string)

	switch {

	case len(template) == 1:

		tplName = template[0]

	case len(template) == 2:

		tplName = template[0]
		if template[1] != "" {
			c.LayoutSections["footerjs"] = template[1]
		}

	case len(template) == 3:
		tplName = template[0]

		if template[1] != "" {
			c.LayoutSections["footerjs"] = template[1]
		}

		layout = template[2]
	}

	if tplName == "" {
		ctrName, actName := c.GetControllerAndAction()
		//不要Controller这个10个字母
		ctrlName := strings.ToLower(ctrName[0 : len(ctrName)-10])
		actionName := strings.ToLower(actName)
		tplName = "api/" + ctrlName + "/" + actionName + ".html"
	}

	c.Layout = layout
	c.TplName = tplName
}


